﻿/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qevent.h>
#include <QPainter>
#include <QTextStream>
#include <QUndoStack>
#include "JistDocument.h"
#include "MoveData.h"
#include <QtGui>
#include <QMessageBox>
#include <QFileDialog>

#include "AddCell.h"
#include "JistAniTool.h"

#include "../libtiled/mapobject.h"
#include "../libtiled/objectgroup.h"
// 무조건 pvr 사용
#define PNG_BIG_SIZE (1*1)

QImage g_EmptyImage;
QString ImageData = QLatin1String("IDt");
QString SpriteData = QLatin1String("objCell");
char* rect_width = "rw";
char* rect_height = "rh";
char* rect_x = "rx";
char* rect_y = "ry";
QString AnimationData = QLatin1String("ADt");
QString SceneData = QLatin1String("SDt");
QString CellData = QLatin1String("CDt");
QString CellData2 = QLatin1String("xxxx");
char* ImgIndex = "Ix";
char* SprIndex = "Sx";
char* pos_x = "px";
char* pos_y = "py";
char* pos_z = "pz";
char* alphaStr = "al";
char* scaleStr = "sc";
char* rotStr = "ro";
char* flip_h = "fh";
char* flip_v = "fv";
char* effStr = "ef";
char* oX = "oX";
char* oY = "oY";
char* dXStr = "dX";
char* dYStr = "dY";
char* scaleXStr = "sX";
char* scaleYStr = "sY";
/*===============================================================================
                                 Document
================================================================================*/

JistDocument::JistDocument(QWidget *parent)
    : QWidget(parent), m_currentIndex(-1), m_mousePressIndex(-1), m_resizeHandlePressed(false)
    ,m_iCurrentSpriteDataIndex(0)
    ,m_iCurrentSceneDataIndex(0)
    ,m_iPreSceneDataIndex(0)
    ,m_iCurrentCellDataIndex(0)
    ,m_pFrameSprite(0)
    ,m_SpriteTableWidget(0)
    ,m_AnimaionTableWidget(0)
    ,m_SceneTableWidget(0)
    ,m_CellTableWidget(0)
    ,m_fCurrentVersion(1.00)
    ,m_iEnermyMonType(0)
    ,m_isBG_EditMode(0)
    ,m_isLoading(0)
    ,m_isAddedResource(0)
{
    m_undoStack = new QUndoStack(this);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Base);

    QPalette pal = palette();
    //pal.setBrush(QPalette::Base, QPixmap(":/icons/background.png"));
    pal.setColor(QPalette::HighlightedText, Qt::red);
    setPalette(pal);
    // 스프라이트 유닛뷰
    m_SpriteUnitFigure = new FigureEditor();
    m_SpriteUnitFigure->setAlignment(Qt::AlignAbsolute);
    m_SpriteUnitFigure->setMovableTouch(false);
    // 스프라이트 영역 정보 이용시 활성화
    m_SpriteUnitFigure->setAdditive(true);
    m_SpriteUnitFigure->setViewMode(SPRITE_VIEW);
    m_SpriteUnitFigure->setDocument(this);
    // 신 뷰
    m_pSceneFrameFigure = new FigureEditor();
    m_pSceneFrameFigure->m_bShowGrid = true;
    m_pSceneFrameFigure->setRect(QRect(0,0,960,640));
    m_pSceneFrameFigure->setModel(&m_CellListModel);
    //m_pSceneFrameFigure->setAlignment(Qt::AlignAbsolute);
    // 벡터 초기 사이즈 지정
    m_SpriteData.resize(m_iCurrentSpriteDataIndex + 1);
    m_SceneData.resize(m_iCurrentSceneDataIndex + 1);
    m_CellData.resize(m_iCurrentSceneDataIndex + 1);
    m_CellData[m_iCurrentSceneDataIndex].resize(m_iCurrentCellDataIndex + 1);

    // 언두스택관리용
    m_pSceneFrameFigure->setDocument(this);

    //connect(&m_pSceneFrameFigure->m_canvas, SIGNAL(changed(const QList<QRectF> &)), this,  SLOT(currentIndexChanged()));
    connect(m_undoStack, SIGNAL(cleanChanged(bool)), SLOT(currentIndexChanged()));
    QString emptyImage[2] = {QLatin1String(":images/16x16/window-close.png"), QLatin1String(":/images/bigMon.png")};
    g_EmptyImage = QImage(emptyImage[0]);
}

bool JistDocument::isModified() const
{
    return (!m_undoStack->isClean() || m_isAddedResource);
}
FigureEditor* JistDocument::getSpriteFigure()
{
    return m_SpriteUnitFigure;
}

void JistDocument::currentIndexChanged()
{
 //     isModified();

//    if (mSceneWithTool) {
//        mSceneWithTool->disableSelectedTool();
//        mSceneWithTool = 0;
//    }

//    MapDocument *mapDocument = currentDocument();

//    if (mapDocument)
//        mUndoGroup->setActiveStack(mapDocument->undoStack());

    emit currentDocumentChanged(/*mapDocument*/);

//    if (MapScene *mapScene = currentMapScene()) {
//        mapScene->setSelectedTool(mSelectedTool);
//        mapScene->enableSelectedTool();
//        mSceneWithTool = mapScene;
//    }
}



static QString toImageFileFilter(const QList<QByteArray> &formats)
{
    QString filter(QCoreApplication::translate("Utils", "Image files"));
    filter += QLatin1String(" (");
    bool first = true;
    foreach (const QByteArray &format, formats) {
        if (!first)
            filter += QLatin1Char(' ');
        first = false;
        filter += QLatin1String("*.");
        filter += QString::fromLatin1(format.toLower());
    }
    filter += QLatin1Char(')');
    return filter;
}
// 이미지추가하기
void JistDocument::OpenImage()
{

    //if(!dir.exists())
    if(m_strDocName.isEmpty())
    {
        QTextCodec *codec = QTextCodec::codecForName("UTF-8");
        QString localeStr = codec->toUnicode("저장할 파일부터 새로 만드세요.");
        QMessageBox::information(m_ImageTableWidget, tr("Notice!"),localeStr);
        return;
    }

    QDir dir = QDir::current();
    const QString filter = toImageFileFilter(QImageReader::supportedImageFormats());
    QString filePath = QFileDialog::getOpenFileName(m_ImageTableWidget, tr("Load Image"), tr(""));//, filter);
    QString relativePath;

    relativePath = dir.relativeFilePath(filePath);
    if(!relativePath.contains(QLatin1String(".ans"))){

        if(!filePath.isEmpty())
        {
            addSpriteList(relativePath);
        }

        /*
        if (!f.isEmpty()) {
            mUi->image->setText(f);
            mPath = f;

            if (!mNameWasEdited)
                mUi->name->setText(QFileInfo(f).completeBaseName());
        }
        */
    }
    else
    {
        QString fileName = filePath;
//        if(fileName.isEmpty())
//            fileName = QFileDialog::getOpenFileName(this, tr(" Load File"),"", tr("save files (*.ans)"));

        if (!fileName.isEmpty()) {

            QFile file(fileName);

            if (!file.open(QIODevice::ReadOnly)) {
                QMessageBox::information(m_ImageTableWidget, tr("Unable to open file"), file.errorString());
               // return;// false;
            }
            loadImageSet(&file, fileName);
            //setDocName(fileName);
            m_undoStack->clear();
            //return;// true;
        }
    }
    emit currentDocumentChanged(/*mapDocument*/);
}


JistDocument::~JistDocument()
{

}


QUndoStack *JistDocument::undoStack() const
{
    return m_undoStack;
}

void JistDocument::mousePressEvent(QMouseEvent *event)
{
    event->accept();
}

void JistDocument::mouseReleaseEvent(QMouseEvent *event)
{
    event->accept();
    m_mousePressIndex = -1;
}

void JistDocument::mouseMoveEvent(QMouseEvent *event)
{
    event->accept();

    if (m_mousePressIndex == -1)
        return;

    //m_undoStack->push(new SetShapeRectCommand(this, shape.name(), rect));
}

void JistDocument::paintEvent(QPaintEvent *event)
{
    QRegion paintRegion = event->region();
    QPainter painter(this);
    QPalette pal = palette();
}

JistCommonModel* JistDocument::getSpriteListModel()
{
    return &m_SpriteListModel;
}

void JistDocument::setSubTableView(JistTableView *tableWidget, SubTableType type)
{
    switch(type)
    {
        case IMAGE:{
            m_ImageTableWidget = tableWidget;
            break;
        }

        case SPRITE:{
            m_SpriteTableWidget = tableWidget;
            break;
        }

        case ANIMATION:{
            m_AnimaionTableWidget = tableWidget;
            break;
        }
        case SCENE:{
            m_SceneTableWidget = tableWidget;
            break;
        }
        case CELL:{
            m_CellTableWidget = tableWidget;
            break;
        }
    }
}


void JistDocument::setSrcFigure(FigureEditor *editor)
{
    m_pSrcFigure = editor;
	// 소스이미지에서        스프라이트 추가시 도큐먼트 참조함
    m_pSrcFigure->setDocument(this);
}

// 애니메이션 독 만들기위해 추가
void JistDocument::setAniFigure(FigureEditor *editor)
{
    m_pAnimationFigure = editor;
    // UI 애니메이션 관리용
    m_pAnimationFigure->setDocument(this);
}

// 스프라이트 뷰 초기화
void JistDocument::setSpriteFrame(QFrame *widget)
{
    m_pFrameSprite = new QFrame();

    QRect fRect = m_pFrameSprite->frameRect();
    fRect.setWidth(fRect.width()-20);
    fRect.setHeight(fRect.height()-20);
    // 그리드 라인 그리기
    QPen pen(Qt::DotLine);
    pen.setWidth(1);
    pen.setColor(QColor(0,0,0,128));

    m_SpriteUnitFigure->m_canvas.addLine(fRect.width()/2, 0, fRect.width()/2, fRect.height()-1, pen);
    m_SpriteUnitFigure->m_canvas.addLine(0, fRect.height()/2, fRect.width()-1, fRect.height()/2, pen);
}

// 스프라이트 뷰 갱신
void JistDocument::setSpriteView(QModelIndex midx)
{
    if(midx.row() >= 0)
    {
        QRect rect = midx.model()->data(midx, Qt::UserRole).toRect();
        QRectF sceneRect = m_SpriteUnitFigure->m_canvas.sceneRect();
        QImage  cutImage = m_pSpriteDelegate->m_Img.copy(rect);
        if(rect.width() == 0)
            cutImage = g_EmptyImage;
        QRect fRect = m_pFrameSprite->frameRect();
        fRect.setWidth(fRect.width()-20);
        fRect.setHeight(fRect.height()-20);

        m_SpriteUnitFigure->clear();
        m_SpriteUnitFigure->m_canvas.setSceneRect(fRect);
        // 핵심 이걸 호출해야 갱신됨
        m_SpriteUnitFigure->updateGeometry();
        QGraphicsPixmapItem* pi = m_SpriteUnitFigure->setImage(cutImage);
        m_SpriteUnitFigure->SetRectItem();
        pi->setPos((fRect.width() - rect.width())/2,(fRect.height() - rect.height())/2);
        // 그리드 라인 그리기
        QPen pen(Qt::DotLine);
        pen.setWidth(1);
        pen.setColor(QColor(0,0,0,128));
        m_SpriteUnitFigure->m_canvas.addLine(fRect.width()/2, 0, fRect.width()/2, fRect.height(), pen);
        m_SpriteUnitFigure->m_canvas.addLine(0, fRect.height()/2, fRect.width(), fRect.height()/2, pen);
        m_SpriteUnitFigure->centerOn((fRect.width())/2, (fRect.height())/2);

        JistCommonData* currentData = getCurrentSpriteData();
        pen.setStyle(Qt::SolidLine);
        if(m_SpriteUnitFigure->m_ScaleX < 1.0){
            pen.setWidth(1.0/m_SpriteUnitFigure->m_ScaleX);
        }
        pen.setColor(QColor(255,0,0,255));
        m_SpriteUnitFigure->m_AnchorVLine = m_SpriteUnitFigure->m_canvas.addLine(fRect.center().x() - currentData->width()/2 + currentData->m_AnchorPoint.x() + 1, 0,
                                             fRect.center().x() - currentData->width()/2 + currentData->m_AnchorPoint.x() + 1, fRect.height(), pen);
        m_SpriteUnitFigure->m_AnchorHLine = m_SpriteUnitFigure->m_canvas.addLine(0, fRect.center().y() + currentData->height()/2 - currentData->m_AnchorPoint.y() + 1,
                                             fRect.width(), fRect.center().y() + currentData->height()/2 - currentData->m_AnchorPoint.y() + 1, pen);

    }
    else{
        QRect fRect = m_pFrameSprite->frameRect();
        fRect.setWidth(fRect.width()-20);
        fRect.setHeight(fRect.height()-20);
        m_SpriteUnitFigure->clear();
        //this->setGeometry(r);
        m_SpriteUnitFigure->m_canvas.setSceneRect(fRect);
        // 핵심 이걸 호출해야 갱신됨
        m_SpriteUnitFigure->updateGeometry();
        // 그리드 라인 그리기
        QPen pen(Qt::DotLine);
        pen.setWidth(1);
        pen.setColor(QColor(0,0,0,128));
        m_SpriteUnitFigure->m_canvas.addLine(fRect.width()/2, 0, fRect.width()/2, fRect.height(), pen);
        m_SpriteUnitFigure->m_canvas.addLine(0, fRect.height()/2, fRect.width(), fRect.height()/2, pen);
    }
    QModelIndexList selList = m_SpriteTableWidget->selectedIndexes();
    emit changeSelectSprite(selList);
}

void JistDocument::setSpriteDelegate(JistCommonDelegate *delegate)
{
    m_pSpriteDelegate = delegate;
}

void JistDocument::changeSpriteList(int index)
{
    m_iCurrentSpriteDataIndex = index;
    m_SpriteListModel.reset();

    if(m_iCurrentSpriteDataIndex > m_SpriteData.count() - 1){
        m_SpriteData.resize(m_iCurrentSpriteDataIndex + 1);
    }
    // 마지막으로 삭제될때
    if(index >= 0)
        m_SpriteListModel.setDataList(&m_SpriteData[m_iCurrentSpriteDataIndex]);
    m_pSrcFigure->clear();
    m_pSrcFigure->setName(m_ImageData.value(m_iCurrentSpriteDataIndex).m_Name);
    QImage *gi = new QImage(m_ImageData.value(m_iCurrentSpriteDataIndex).m_Name);
    m_pSpriteDelegate->setImage(*gi);
    m_pSrcFigure->setImage(*gi);

    m_SpriteListModel.setViewWiget(m_SpriteTableWidget);

    for(int k = 0; k < getSpriteListModel()->rowCount(); k++)
    {
        const QModelIndex index = getSpriteListModel()->index(k, 0, QModelIndex());
        //불필요한 체크박스 제거
        //m_SpriteTableWidget->openPersistentEditor(index);
    }

    m_SpriteTableWidget->refineView(0);
}

void JistDocument::changeSceneList(int index)
{
    m_iCurrentSceneDataIndex = index;
    // 애니메이션
    m_pAnimationFigure->resetAni();
    m_pAnimationFigure->m_iAnimationIndex = m_iCurrentSceneDataIndex;

    m_SceneListModel.reset();
    if(m_iCurrentSceneDataIndex > m_SceneData.count() - 1){
        m_SceneData.resize(m_iCurrentSceneDataIndex + 1);
    }
    if(index >= 0)
        m_SceneListModel.setDataList(&m_SceneData[m_iCurrentSceneDataIndex]);
    m_SceneListModel.setViewWiget(m_SceneTableWidget);

    if(m_SceneListModel.rowCount() == 0)
    {
        m_CellListModel.reset();
        if(m_iCurrentSceneDataIndex > m_CellData.size() - 1)
        {
            m_CellData.resize(m_iCurrentSceneDataIndex + 1);
            m_CellData[m_iCurrentSceneDataIndex].resize(0 + 1);
        }
        // 셀리스트 삭제 버그 수정
        if(index >= 0)
            m_CellListModel.setDataList(&m_CellData[m_iCurrentSceneDataIndex][0]);
    }

    for(int k = 0; k < m_SceneListModel.rowCount(); k++)
    {
        const QModelIndex index = m_SceneListModel.index(k, 0, QModelIndex());
        //불필요한 체크박스 제거
        //m_SceneTableWidget->openPersistentEditor(index);
    }
    // 파일로드시 이전신이 표시되는 현상제거
    for(int i = 0; m_iPreSceneDataIndex < m_CellData.count() && i < (m_CellData[m_iPreSceneDataIndex]).count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iPreSceneDataIndex][i].count(); k++)
        {
            // 현재 셀 비표시하기
            // 애니메이션 관련
            //(m_CellData[m_iPreSceneDataIndex][i][k]).m_pIItem->setVisible(false);
            // 애니메이션 관련
            if(!m_AnimationData[m_iPreSceneDataIndex].m_bVisible)
                m_pSceneFrameFigure->m_canvas.removeItem(m_CellData[m_iPreSceneDataIndex][i][k].m_pIItem);
        }
    }

    m_SceneTableWidget->refineViewNoUndo(0);
    m_iPreSceneDataIndex = m_iCurrentSceneDataIndex;
    m_iCurrentCellDataIndex = 0;
}

void JistDocument::changeCellList(int index)
{
    for(int i = 0; m_iPreSceneDataIndex < m_CellData.count() && i < (m_CellData[m_iPreSceneDataIndex]).count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iPreSceneDataIndex][i].count(); k++)
        {
            // 현재 셀 비표시하기
            // 애니메이션 관련
            //(m_CellData[m_iPreSceneDataIndex][i][k]).m_pIItem->setVisible(false);
            // 애니메이션 관련
            // 누적 선택 모드
            if(!m_isBG_EditMode && !m_AnimationData[m_iPreSceneDataIndex].m_bVisible)
                m_pSceneFrameFigure->m_canvas.removeItem(m_CellData[m_iPreSceneDataIndex][i][k].m_pIItem);
        }
    }

    m_iCurrentCellDataIndex = index;

    // 모델을 먼저 리셋해야함
    m_CellListModel.reset();
    // 모델리셋후 벡터 리사이즈
    if(m_iCurrentSceneDataIndex >= 0 && m_iCurrentCellDataIndex > m_CellData[m_iCurrentSceneDataIndex].count() - 1)
    {
        m_CellData[m_iCurrentSceneDataIndex].resize(m_iCurrentCellDataIndex + 1);
    }

    if(index >= 0 && m_iCurrentSceneDataIndex >= 0)
        m_CellListModel.setDataList(&m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex]);
    m_CellListModel.setViewWiget(m_CellTableWidget);

    // 신뷰 다시 그리기
    //m_pSceneFrameFigure->clear();
    for(int k = 0; k < m_CellListModel.rowCount() && m_iCurrentCellDataIndex >= 0 && m_iCurrentSceneDataIndex >= 0; k++)
    {
        const QModelIndex index = m_CellListModel.index(k, 0, QModelIndex());
        m_CellTableWidget->openPersistentEditor(index);
        // 현재 셀 표시하기
        // 애니메이션 관련
        //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][k].m_pIItem->setVisible(true);
        // 아이템이 추가되지만
        //If the item is already in a different scene,
        //it will first be removed from its old scene, and then added to this scene as a top-level.
        if(!m_isLoading)
            m_pSceneFrameFigure->addItem(m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][k].m_pIItem);
    }
    printf("======================= %d ========================================\n", index);
    m_CellTableWidget->refineView(-1);

    // 리스트뷰와 셀렉팅연동
    m_pSceneFrameFigure->m_Selectlist = m_pSceneFrameFigure->m_canvas.selectedItems();
    if(!m_pSceneFrameFigure->m_Selectlist.isEmpty()){
        qSort(m_pSceneFrameFigure->m_Selectlist.begin(), m_pSceneFrameFigure->m_Selectlist.end());
        m_CellTableWidget->clearSelection();
    }
    //
    m_CellTableWidget->setSelectionMode(QAbstractItemView::MultiSelection);
    int selectCnt = m_pSceneFrameFigure->m_Selectlist.count();
    // 선택된 셀을 다른 신과 중복되지 않게 바인드
    QMap< int, int > monSpeedMap;
    typedef std::pair <int, int> IntPair;
    for(int k = 0; k < selectCnt && k < m_pSceneFrameFigure->m_Selectlist.count(); k++){
        ImageItem* item = (ImageItem*)m_pSceneFrameFigure->m_Selectlist[k];
        int id = item->getId();//zValue();
        int zV =  item->zValue();
        if(zV == m_iCurrentSceneDataIndex )
            monSpeedMap.insert(id, id);
    }
    int mCnt = monSpeedMap.size();
    // 인덱스로 접근하기 위해 리스트 사용
    QList < int > idValues = monSpeedMap.values();
    for(int k = 0; k < mCnt; k++){
        int id = idValues.at(k);
        // 누적 선택 모드에서 셀렉팅연동
        if(id < m_CellListModel.m_pList->count())
        {
              m_CellTableWidget->selectRow(id);
        }
        //m_CellTableWidget->setSelection(QRect(0, id* (JistCommonDelegate::m_PixelSize + 1) , 1, 1),QItemSelectionModel::Select);
    }

    m_CellTableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
    // 처음 로드시 0번째 셀리스트 선택 안되는 버그 수정
    // 0.9961 버전에서 제외
//    if(m_pSceneFrameFigure->m_Selectlist.count() && m_isLoading){
//        ImageItem* item = (ImageItem*)m_pSceneFrameFigure->m_Selectlist.first();
//        if(m_CellTableWidget->currentIndex().row() != item->getId())
//            m_CellTableWidget->selectRow(m_CellTableWidget->currentIndex().row());
//    }
}

void JistDocument::changeCellData( const QItemSelection & selected, const QItemSelection & deselected )
{

    QModelIndexList deselList = deselected.indexes();
    for(int k = 0; k < deselList.count()&& m_iCurrentCellDataIndex >= 0 && m_iCurrentSceneDataIndex >= 0; k++){
        int deselIndex = deselList.at(k).row();
        if(m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][deselIndex].m_pIItem){
            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][deselIndex].m_pIItem->setSelected(false);
        }
    }
    int selIndex = -1;
    QModelIndexList selList = m_CellTableWidget->selectedIndexes();
     for(int k = 0; k < selList.count() && m_iCurrentCellDataIndex >= 0 && m_iCurrentSceneDataIndex >= 0; k++){
        selIndex = selList.at(k).row();
        if(m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][selIndex].m_pIItem)
                //&& !m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][selIndex].m_pIItem->isSelected())
        {
            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][selIndex].m_pIItem->setSelected(true);
            //emit changeSelectCell(&m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][selIndex]);
        }
    }
    m_pSceneFrameFigure->m_Selectlist = m_pSceneFrameFigure->m_canvas.selectedItems();
    // 하나의 아이템만 선택되고 보이는 것만 셀인포에이션 독에 정보를 표시
    QList<QGraphicsItem*> list = m_pSceneFrameFigure->items();
    int cnt = list.count();
    int svCnt = 0;
    for(int k = 0; k < cnt; k++){
        if(list.at(k)->isSelected() && list.at(k)->isVisible())
            svCnt++;
    }
    //if(svCnt >= 1)
    {
        qSort(selList.begin(), selList.end());
        emit changeSelectCell(selList);
    }
}
// 이미지추가
bool JistDocument::addSpriteList(QString path)
{
    // 스프라이트 추가및 확인관련 클래스 설정

    QFile file(path);
    file.open(QIODevice::ReadOnly);

    QImage *gi = new QImage(path);
    if(gi->isNull()){
        if(g_CMDLINEMode)
        {
            gi = &g_EmptyImage;
        }
        else{
#ifdef HARD_VESION
        gi = &g_EmptyImage;
#else
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString localeStr = codec->toUnicode("경로를 확인하세요.");
            localeStr +=  path;
            QMessageBox::information(m_ImageTableWidget, tr("Notice!"),localeStr);
            file.close();

            return false;
#endif
        }
    }
    m_pSrcFigure->clear();
    m_pSrcFigure->setName(path);
    //QImage baseImg =  QImage(gi->size(), QImage::Format_ARGB32_Premultiplied);
    //baseImg.load(m_pSrcFigure->getName());

    m_pSpriteDelegate->setImage(*gi);
    m_pSrcFigure->setImage(*gi);
    m_pSrcFigure->setModel(getSpriteListModel());
    m_pSrcFigure->setAdditive(true);
    // wonder_run 미사용
//    if(gi->width() * gi->height() > PNG_BIG_SIZE)
//        m_pSrcFigure->creatFakeBMP();
    m_SpriteUnitFigure->clear();

    // 리스트 데이터 인덱스 관련 설정
    //m_iModelCount++;
    //m_iCurrentSpriteDataIndex = m_iModelCount-1;
    //getSpriteListModel()->setImgFilePath(&path);

    // 디폴트 데이터 추가
    JistCommonData data;
    data.m_bVisible = true;
    data.m_Name = path;
    data.m_img = gi->convertToFormat(QImage::Format_ARGB32);
    // 게임상 에서 파싱중 텍스쳐 로딩여부
    const QXmlStreamAttributes atts = xml.attributes();
    if(atts.count() && m_fLoadingVersion >= 0.990)
            data.m_bVisible = atts.value(QLatin1String("fixView")).toString().toInt();
    //data.m_Rect = m_SelectRect;
    data.m_iImgIndex = m_ImageData.count();
    m_ImageListModel.addData(data);
    m_ImageData.last().m_iImgIndex =  data.m_iImgIndex;
    m_isAddedResource = true;
    return true;
 }

void JistDocument::addAnimation(QString name, bool isLoading)
{
    JistCommonData data;
    data.m_bVisible = false;
    if(isLoading){
        const QXmlStreamAttributes atts = xml.attributes();
        data.m_bVisible = atts.value(QLatin1String("fixView")).toString().toInt();
    }
    data.m_Name = name;
    //data.m_Rect = m_SelectRect;

    int curCnt = m_CellData[m_iPreSceneDataIndex][m_iCurrentCellDataIndex].count();
    if(m_CellData[m_iPreSceneDataIndex][m_iCurrentCellDataIndex].count() > 0 )//&& item.count() > 0)
    {
        for(int k = 0; k < curCnt; k++)
        {
            //m_CellData[m_iPreSceneDataIndex][m_iCurrentCellDataIndex][k].m_pIItem->setVisible(false); // 이전 셀들 비표시
            m_pSceneFrameFigure->m_canvas.removeItem(m_CellData[m_iPreSceneDataIndex][m_iCurrentCellDataIndex][k].m_pIItem);
        }
    }
    m_AniListModel.addData(data);
    //m_pSceneFrameFigure->clear();
}

void JistDocument::addScene(bool isLoad)
{
    if(isLoad){
        JistCommonData data;
        // UI를 제작을 위한 고정애니메이션 표시 여부
        const QXmlStreamAttributes atts = xml.attributes();
        data.m_bVisible = atts.value(QLatin1String("fixView")).toString().toInt();
        data.m_Name = atts.value(QLatin1String("name")).toString();
        //data.m_bVisible = true;
        //data.m_Name = "Scene";
        m_SceneListModel.addData(data);
    }else{
        m_SceneTableWidget->m_isUndoAction = false;
        QList < JistCommonData > tempScene;
        JistCommonData data;
        data.m_bVisible = false;
        QUndoCommand *cmd =  new AddCellList(this, m_SceneListModel.rowCount(), m_SceneTableWidget, &tempScene, &data);
        cmd->setText(tr("Add Scene"));
        undoStack()->push(cmd);
    }
}

void JistDocument::addShadowCell(int iX, int iY)
{
    if(m_SceneTableWidget->currentIndex().row()<0)
        return;
    JistCommonData data;
    {
        data.m_bVisible = true;
        data.m_iImgIndex = m_iCurrentSpriteDataIndex;
        data.m_iSpriteIndex = m_SpriteTableWidget->currentIndex().row();

        ImageItem* i = new ImageItem(m_iCurrentSpriteDataIndex, m_SpriteTableWidget->currentIndex().row(), &m_SpriteData);
        int aniId = m_AnimaionTableWidget->m_iSelectIndex;
        i->setZValue(aniId + (m_CellListModel.rowCount() - 1) * 0.0001f);

        data.m_pIItem = i;
	//애니메이션의 정렬 인덱스를 따라감
        data.m_pIItem->m_oIndex_X = iX;
        data.m_pIItem->m_oIndex_Y = iY;
        //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][m_CellListModel.rowCount() - 1] = data;

        JistCommonData srcData = m_SpriteData[m_iCurrentSpriteDataIndex].value(m_SpriteTableWidget->currentIndex().row());
        data.m_Rect = srcData.m_Rect;
        data.m_img = srcData.m_img;
        data.m_pIItem->m_composition_mode = QPainter::CompositionMode_Multiply;
    }
    QUndoCommand *cmd =  new AddShadowCell(this, 0, m_CellTableWidget, &data);
    cmd->setText(tr("Add ShadowCell"));
    undoStack()->push(cmd);
}

JistCommonData* JistDocument::getCurrentSpriteData()
{
    int rowIndex = m_SpriteTableWidget->currentIndex().row();
    JistCommonData* srcData = NULL;
    if(rowIndex != -1 && m_iCurrentSpriteDataIndex > -1)
        srcData = &m_SpriteData[m_iCurrentSpriteDataIndex][rowIndex];

    return  srcData;
}

void JistDocument::addCell(bool isEmpty)
{
    //m_CellTableWidget->emitChangeSelectRow(m_iCurrentCellDataIndex);

    if(m_SceneTableWidget->currentIndex().row()<0)
        return;
    JistCommonData data;
    // 빈셀 추가 여부
    if(!isEmpty){
        data.m_bVisible = true;
        //data.m_Name = "Cell";

        //data.m_Pos = srcData.m_Pos;
        //data.m_Zlayer = m_CellListModel.rowCount() - 1;
        data.m_iImgIndex = m_iCurrentSpriteDataIndex;
        data.m_iSpriteIndex = m_SpriteTableWidget->currentIndex().row();
        //ImageItem* i = new ImageItem(&data.m_img);
        ImageItem* i = new ImageItem(m_iCurrentSpriteDataIndex, m_SpriteTableWidget->currentIndex().row(), &m_SpriteData);
        int aniId = m_AnimaionTableWidget->m_iSelectIndex;
        i->setZValue(aniId + (m_CellListModel.rowCount() - 1) * 0.0001f);
        i->setId(m_CellListModel.rowCount() - 1);
        //m_pSceneFrameFigure->m_canvas.addItem(i);
        //m_CellListModel.addData(data);
        data.m_pIItem = i;
        //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][m_CellListModel.rowCount() - 1] = data;

        JistCommonData srcData = m_SpriteData[m_iCurrentSpriteDataIndex].value(m_SpriteTableWidget->currentIndex().row());
        data.m_Rect = srcData.m_Rect;
        data.m_img = srcData.m_img;
    }else{
        //memset(&data,0,sizeof(JistCommonData));
        ImageItem* i = new ImageItem(0, 0, &m_SpriteData);
        int aniId = m_AnimaionTableWidget->m_iSelectIndex;
        i->setZValue(aniId + (m_CellListModel.rowCount() - 1) * 0.0001f);
        i->setId(m_CellListModel.rowCount() - 1);
        data.m_iImgIndex = -1;
        data.m_iSpriteIndex = -1;
        QString emptyImage[2] = {tr(":images/16x16/window-close.png"), tr(":/images/bigMon.png")};
        data.m_img = QImage(emptyImage[0]);
        //i->setRect(0,0,0,0);
        data.m_pIItem = i;
    }
    QUndoCommand *cmd =  new AddCell(this, m_CellListModel.rowCount(), m_CellTableWidget, &data);
    cmd->setText(tr("Add Cell"));
    undoStack()->push(cmd);
}

//=========================== 셀 정보 수정 =======================
ImageItem* JistDocument::getCurrentCell()
{
    if(m_CellTableWidget->currentIndex().row() < 0)
        return NULL;
    else
        return m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][m_CellTableWidget->currentIndex().row()].m_pIItem;
}

QModelIndexList JistDocument::getSelectCellList()
{
    // 1개만 선택
    //QModelIndexList selectedList = m_CellTableWidget->selectedIndexes().mid(0,1);
    // 다중선택
    QModelIndexList selectedList = m_CellTableWidget->selectedIndexes();
    qSort(selectedList.begin(), selectedList.end());
    m_selectCellList = selectedList;
    return m_selectCellList;
}

QList<QGraphicsItem*> JistDocument::getSelectItemList()
{
    QList<QGraphicsItem*> tempList = m_pSceneFrameFigure->items();
    QList<QGraphicsItem*> selectedList;
    // 1개만 선택
    //QModelIndexList selectedList = m_CellTableWidget->selectedIndexes().mid(0,1);
    // 다중선택

    for(int k = 0; k < tempList.count(); k++){
        QGraphicsItem *tempItem = tempList.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            selectedList.append(tempItem);
            if(!g_MultiEditMode){
                break;
            }
        }
    }
    m_BeVisibleItemList = selectedList;
    return m_BeVisibleItemList;
}

void JistDocument::setCellEffect(int eff)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;

//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//    //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_composition_mode = eff;
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->update();
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);
            item->m_composition_mode = eff;
            if(item->m_TextItem){
                item->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
                switch(eff)
                {
                    case 100:
                    {
                        item->m_TextItem->setDefaultTextColor(QColor(225, 182, 52));
                    }
                    break;
                    case 101:
                    {
                        item->m_TextItem->setDefaultTextColor(QColor(145, 185, 3));
                    }
                    break;
                    case 102:
                    {
                        item->m_TextItem->setDefaultTextColor(QColor(163, 95, 198));
                    }
                    break;
                    case 103:
                    {
                        item->m_TextItem->setDefaultTextColor(QColor(2, 15, 41));
                    }
                    break;
                }
            }
            else
                item->update();
        }

    }
}

void JistDocument::setCellAlpha(int val)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//    //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->setOpacity(val/100.0f);
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);
            item->setOpacity(val/100.0f);
        }
    }
}

void JistDocument::setCellScale(int val)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//    //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->setScale(val/100.0f);
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);
            item->setScale(val/100.0f);
        }
    }
}

void JistDocument::setCellScaleX(int val)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//    //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();

//        if(m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem){
//            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
//            QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
//            QFont font( localeStr, 10 * val/100.0f );
//            //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->font().setPointSize(10 * val/100.0f);
//            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->setFont( font );
//            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
//            m_ScaleYSpinBox->setValue(val);
//        }
//        else
//            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->setScaleX(val/100.0f);
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);
            if(item->m_TextItem){
                QTextCodec *codec = QTextCodec::codecForName("UTF-8");
                QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
                QFont font( localeStr, g_FontSize * val/100.0f + 0.5 );
                //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->font().setPointSize(10 * val/100.0f);
                item->m_TextItem->setFont( font );
                item->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
                m_ScaleYSpinBox->setValue(val);
                setAnchorTextItem(item->m_iAnchor);
            }
            else
                item->setScaleX(val/100.0f);
        }
    }
}

void JistDocument::setCellScaleY(int val)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//    //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();
//        if(m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem){
//            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
//            QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
//            QFont font( localeStr, 10 * val/100.0f );
//            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->setFont( font );
//            //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->font().setPointSize(10 * val/100.0f);
//            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
//            m_ScaleXSpinBox->setValue(val);
//        }
//        else
//            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->setScaleY(val/100.0f);
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);
            if(item->m_TextItem){
                QTextCodec *codec = QTextCodec::codecForName("UTF-8");
                QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
                QFont font( localeStr, g_FontSize * val/100.0f + 0.5 );
                //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem->font().setPointSize(10 * val/100.0f);
                item->m_TextItem->setFont( font );
                item->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
                m_ScaleXSpinBox->setValue(val);
                setAnchorTextItem(item->m_iAnchor);
            }
            else
                item->setScaleY(val/100.0f);
        }
    }
}


void JistDocument::setCellRotate(int val)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//    //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->setRotation(val);
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);
            item->setRotation(val);
        }
    }
}

void JistDocument::setCellMirror(bool horizontally, bool vertically)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
//    QModelIndexList selectedList = getSelectCellList();
//    for(int k = 0; k < selectedList.count(); k++){
//        //if(!selectedList.isEmpty()){
//        int id = selectedList.at(k).row();
//        JistCommonData data = m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].at(id);
//        data.m_pIItem->m_FlipH = horizontally ? !data.m_pIItem->m_FlipH : data.m_pIItem->m_FlipH;
//        data.m_pIItem->m_FlipV = vertically ? !data.m_pIItem->m_FlipV : data.m_pIItem->m_FlipV;
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_FlipH = data.m_pIItem->m_FlipH;
//        m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_FlipV = data.m_pIItem->m_FlipV;

//        ImageItem *item = (ImageItem*)data.m_pIItem;

//        item->m_Image = item->m_Image.mirrored(horizontally, vertically);
//        item->update();
//    }

    QList<QGraphicsItem*> list = getSelectItemList();
    for(int k = 0; k < list.count(); k++){
        QGraphicsItem *tempItem = list.at(k);
        if(tempItem->isSelected() && tempItem->isVisible()){
            ImageItem* item = (ImageItem*)(tempItem);

            item->m_FlipH = horizontally ? !item->m_FlipH : item->m_FlipH;
            item->m_FlipV = vertically ? !item->m_FlipV : item->m_FlipV;
            item->m_FlipH = item->m_FlipH;
            item->m_FlipV = item->m_FlipV;

            ImageItem *tempItem = (ImageItem*)item;
            tempItem->m_Image = tempItem->m_Image.mirrored(horizontally, vertically);
            tempItem->update();
        }
    }
}

void JistDocument::setDocName(QString fileName)
{
    m_strDocName = fileName;
}

QString JistDocument::getDocName()
{
    return m_strDocName;
}

void JistDocument::saveFile(QString path)
{
    // 세이브 파일 재설정
    {
        ImageData = tr("IDt");
        SpriteData = tr("objCell");
        rect_width = ("rw");
        rect_height = ("rh");
        rect_x = ("rx");
        rect_y = ("ry");
        AnimationData = tr("ADt");
        SceneData = tr("SDt");
        CellData = tr("CDt");

        ImgIndex = ("Ix");
        SprIndex = ("Sx");
        pos_x = ("px");
        pos_y = ("py");
        pos_z = ("pz");
        alphaStr = ("al");
        scaleStr = ("sc");
        rotStr = ("ro");
        flip_h = ("fh");
        flip_v = ("fv");
        effStr = ("ef");
        oX = "oX";
        oY = "oY";
        dXStr = "dX";
        dYStr = "dY";
        scaleXStr = "sX";
        scaleYStr = "sY";
    }

    QString fileName = path;
    if(!fileName.compare(tr("new"))){
            fileName = QFileDialog::getSaveFileName(m_ImageTableWidget, tr(" Save File"), tr(""), tr("save files (*.ans)"));
            if(!fileName.isEmpty())
                newDocument();
    }

    if(!fileName.compare(tr("new_name"))){
            fileName = QFileDialog::getSaveFileName(m_ImageTableWidget, tr(" Save File"), tr(""), tr("save files (*.ans)"));
    }

    if(!fileName.isEmpty()){

        setDocName(fileName);
        QDir dirC(m_strDocName);
        QString curFilneName = dirC.dirName();
        QString curPath = m_strDocName;
        curPath.remove(curFilneName);
        bool r = QDir::setCurrent(curPath);

        QDir dir = QDir::current();
        QString relativePath;
        relativePath = dir.relativeFilePath(fileName);
        QString saveName = fileName;

        // 텍스트 교체 애니메이션(애니메이션 파일에서는 텍스쳐를 사용하지 않지만 게임 내부적으로 텍스쳐을 교체하여 사용함
        if(saveName.contains(tr(".anst")))
        {
            saveName.chop(1);
        }

        if(g_isBinSave){
               saveName.chop(3);
               saveName.append(tr("abin"));
        }

        QFile file(saveName);
        QString backupFileName = fileName;
        // 백업파일 만들기
        file.copy(backupFileName.insert(backupFileName.length() - 4, tr("[!]")));
        if (!g_isSaveDividAni && !file.open(QIODevice::WriteOnly)) {
            QMessageBox::information(m_ImageTableWidget, tr("Unable to open file"), file.errorString());
            return;
        }
        saveAniUnion(&file, fileName);
        file.close();

        // 정상종료 하면 백업파일제거
        QFile backUpFile(backupFileName);
        backUpFile.remove();
        m_undoStack->clear();
        m_isAddedResource = false;
    }
}
// 애니메이션, 신, 셀 삭제시 임시세이브파일 보존
void JistDocument::saveTempFile(QString path)
{
    // 세이브 파일 재설정
    {
        ImageData = tr("IDt");
        SpriteData = tr("objCell");
        rect_width = "rw";
        rect_height = "rh";
        rect_x = "rx";
        rect_y = "ry";
        AnimationData = tr("ADt");
        SceneData = tr("SDt");
        CellData = tr("CDt");

        ImgIndex = "Ix";
        SprIndex = "Sx";
        pos_x = "px";
        pos_y = "py";
        pos_z = "pz";
        alphaStr = "al";
        scaleStr = "sc";
        rotStr = "ro";
        flip_h = "fh";
        flip_v = "fv";
        effStr = "ef";
        oX = "oX";
        oY = "oY";
        dXStr = "dX";
        dYStr = "dY";
        scaleXStr = "sX";
        scaleYStr = "sY";
    }

    QString fileName = path;
    if(fileName.isEmpty())
            fileName = QFileDialog::getSaveFileName(m_ImageTableWidget, tr(" Save File"), tr(""), tr("save files (*.ans)"));
    setDocName(fileName);
    QDir dirC(m_strDocName);
    QString curFilneName = dirC.dirName();

    QString curPath = m_strDocName;
    curPath.remove(curFilneName);
    bool r = QDir::setCurrent(curPath);

    QDir dir = QDir::current();
    QString relativePath;
    relativePath = dir.relativeFilePath(fileName);
    if (!fileName.isEmpty()) {

        //QString backupFileName = fileName.insert(fileName.length() - 4, "[!!]");
        QString backupFileName = fileName.append(tr("bak"));
        QFile file(backupFileName);

        if (!file.open(QIODevice::WriteOnly)) {
            QMessageBox::information(m_ImageTableWidget, tr("Unable to open file"), file.errorString());
            return;
        }
        saveAniUnion(&file, backupFileName);
        file.close();
    }
}

static QXmlStreamWriter *createWriter(QIODevice *device)
{
    QXmlStreamWriter *writer = new QXmlStreamWriter(device);
    writer->setAutoFormatting(true);
    writer->setAutoFormattingIndent(1);
    return writer;
}

void JistDocument::saveAniUnion(QIODevice *device, QString &path)
{

    // 신프레임네의 각 스프라이트의 좌표 설정
    QList<QGraphicsItem *> item = m_pSceneFrameFigure->m_canvas.items();
    int curCnt = m_CellData[m_iPreSceneDataIndex][m_iCurrentCellDataIndex].count();
    if(m_CellData[m_iPreSceneDataIndex][m_iCurrentCellDataIndex].count() > 0)// && item.count() > 0)
    {
        int cnt = item.count();
        for(int k = 0; k < curCnt; k++)
        {
            QPointF fp = ((m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][k]).m_pIItem)->pos();
            //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][k].m_Pos = QPoint(fp.x(), fp.y()); //순서를 맞춰야함
        }
    }
    // 바이너리로 만드는 것은 최대한 불필요한 데이터를 제거함
    // 스프라이트리스트 정리
    if(g_isBinSave){
        if(path.contains(tr(".anst"))){
            path.chop(1);
        }
        else{
            m_SpriteTableWidget->spriteListRefine();
        }
    }
    if(g_isSaveDividAni){
        for(m_iSavigAniIdnex = 0; m_iSavigAniIdnex < m_AnimationData.count(); m_iSavigAniIdnex++)
        {
            JistCommonData data = m_AnimationData.value(m_iSavigAniIdnex);
            if(data.m_Name.contains(tr("@")))
                continue;
            QString tempName = path;
            tempName.chop(4);
            tempName.append(tr("@"));
            tempName.append(data.m_Name);
            tempName.append(tr(".an1"));
            QFile file(tempName);
            if (!file.open(QIODevice::WriteOnly)) {
                QMessageBox::information(m_ImageTableWidget, tr("Unable to open file"), file.errorString());
                return;
            }
            QXmlStreamWriter *writer = createWriter(&file);
            writer->setCodec("UTF-8");
            writer->writeStartDocument();
            saveAniUnionSeveral(*writer, path);
            writer->writeEndDocument();
            delete writer;
        }
    }
    else{
        QXmlStreamWriter *writer = createWriter(device);
        writer->setCodec("UTF-8");
        writer->writeStartDocument();

        //if (mDtdEnabled)
    //    {
    //        writer->writeDTD(QLatin1String("<!DOCTYPE map SYSTEM \"" "http://mapeditor.org/dtd/1.0/"
    //                                       "map.dtd\">"));
    //    }

        saveAniUnion(*writer, path);
        writer->writeEndDocument();
        m_undoStack->clear();
        m_isAddedResource = false;
        delete writer;
    }
}

void JistDocument::saveAniUnion(QXmlStreamWriter &w, const QString &path)
{
    w.setCodec("UTF-8");
    w.writeStartElement(QLatin1String("Ani"));
    w.writeAttribute(QLatin1String("version"), QString(QLatin1String("%1")).arg(m_fCurrentVersion));
    w.writeAttribute(QLatin1String("AniPath"), m_FinalWorkPath);
    // 이미지 정보 저장
    for(int k = 0; k < m_ImageData.count(); k++) {
        JistCommonData data = m_ImageData.value(k);
        saveImageData(w, data, k);
    }

    for(m_iSavigAniIdnex = 0; m_iSavigAniIdnex < m_AnimationData.count(); m_iSavigAniIdnex++) {
        JistCommonData data = m_AnimationData.value(m_iSavigAniIdnex);
        saveAnimationData(w, data, m_iSavigAniIdnex);
    }
	if(g_isBinSave){
		w.writeStartElement(QLatin1String("bidata"));
		// w.writeAttribute(QLatin1String("cnt"), QString::number(m_Binary.count()));
		w.writeEndElement();
	}
    w.writeEndElement();

	//셀 일괄 저장
    for(int k = 0; k < m_Binary.count(); k ++)
    {
        JistCellData temp = m_Binary.at(k);
        w.device()->write((char*)&temp,  sizeof(JistCellData));
    }
    m_Binary.clear();
}


void JistDocument::saveAniUnionSeveral(QXmlStreamWriter &w, const QString &path)
{
    w.setCodec("UTF-8");
    w.writeStartElement(QLatin1String("Ani"));
    w.writeAttribute(QLatin1String("version"), QString(QLatin1String("%1")).arg(m_fCurrentVersion));
    w.writeAttribute(QLatin1String("AniPath"), m_FinalWorkPath);
    // 이미지 정보 저장
    for(int k = 0; k < m_ImageData.count(); k++) {
        JistCommonData data = m_ImageData.value(k);
        saveImageData(w, data, k);
    }

   // for(m_iSavigAniIdnex = 0; m_iSavigAniIdnex < m_AnimationData.count(); m_iSavigAniIdnex++) {
        JistCommonData data = m_AnimationData.value(m_iSavigAniIdnex);
        saveAnimationData(w, data, m_iSavigAniIdnex);
    //}
    if(g_isBinSave){
        w.writeStartElement(QLatin1String("bidata"));
        // w.writeAttribute(QLatin1String("cnt"), QString::number(m_Binary.count()));
        w.writeEndElement();
    }
    w.writeEndElement();

    //셀 일괄 저장
    for(int k = 0; k < m_Binary.count(); k ++)
    {
        JistCellData temp = m_Binary.at(k);
        w.device()->write((char*)&temp,  sizeof(JistCellData));
    }
    m_Binary.clear();
}


void JistDocument::saveImageData(QXmlStreamWriter &w, const JistCommonData &data, int index)
{
    w.writeStartElement(QLatin1String(ImageData.toLatin1()));

    QDir dirC(m_strDocName);
    QString curFilneName = dirC.dirName();
    QString curPath = m_strDocName;
    curPath.remove(curFilneName);

    QString relativePath;
    QDir dir = QDir::current();
    QDir cDir(data.m_Name);
    QString cPath = cDir.path();//dirName();
    curPath.append(cPath);
    relativePath = QDir::cleanPath(curPath);
    relativePath = dir.relativeFilePath(relativePath);

    if(data.m_img.width() * data.m_img.height() > PNG_BIG_SIZE){
        relativePath.replace(tr(".png"), tr(".pvr.gz"), Qt::CaseInsensitive);
    }
    w.writeAttribute(QLatin1String("path"), relativePath);
    // 게임상 에서 파싱중 텍스쳐 로딩여부
    w.writeAttribute(QLatin1String("fixView"), QString::number(data.m_bVisible));
    // 스프라이트 정보 저장
    for (int i = 0; i < m_SpriteData[index].count(); ++i) {
        saveSpriteData(w, m_SpriteData[index].value(i));
    }

    w.writeEndElement();
}

void JistDocument::saveSpriteData(QXmlStreamWriter &w, const JistCommonData &data)
{
    w.writeStartElement(QLatin1String(SpriteData.toLatin1()));

    w.writeAttribute(QLatin1String(rect_x), QString::number(data.m_Rect.x()));
    w.writeAttribute(QLatin1String(rect_y), QString::number(data.m_Rect.y()));
    w.writeAttribute(QLatin1String(rect_width), QString::number(data.m_Rect.width()));
    w.writeAttribute(QLatin1String(rect_height), QString::number(data.m_Rect.height()));
    w.writeAttribute(QLatin1String("UIOpt"), QString::number(data.m_UIOpt));

    w.writeEndElement();
}

//=============================================================================================
void JistDocument::saveAnimationData(QXmlStreamWriter &w, const JistCommonData &data, int index)
{
    w.writeStartElement(QLatin1String(AnimationData.toLatin1()));
    w.writeAttribute(QLatin1String("name"), data.m_Name);
	// 참조 이미지 셀은 바이너리 데이터에서 제외
    if(data.m_Name.contains(tr("@")))
		m_isAddingBinData = false;
    else
		m_isAddingBinData = true;
    // 이펙트 타이밍를 표시를 위한 고정애니메이션 표시 여부
    w.writeAttribute(QLatin1String("fixView"), QString::number(data.m_bVisible));

    // 신 정보 저장
    for (int i = 0; i < m_SceneData[index].count(); ++i) {
        saveSceneData(w, m_SceneData[index].at(i), index, i);
    }
    w.writeEndElement();
}


void JistDocument::saveSceneData(QXmlStreamWriter &w, const JistCommonData &data, int index, int sceneIdx)
{
    w.writeStartElement(QLatin1String(SceneData.toLatin1()));
    w.writeAttribute(QLatin1String("name"), data.m_Name);
    // UI를 제작을 위한 고정신 표시 여부
    w.writeAttribute(QLatin1String("fixView"), QString::number(data.m_bVisible));
    // 셀 정보 저장
	if(!g_isBinSave)
		saveCellData(w, m_CellData[index][sceneIdx], sceneIdx);
	else
		saveCellDataToBinary(w, m_CellData[index][sceneIdx], sceneIdx);

    w.writeEndElement();
}

void JistDocument::saveCellData(QXmlStreamWriter &w, QList< JistCommonData > &listData, int index)
{
    // 정보 저장
    int imgOffset = this->m_iCurrentSpriteDataIndex;
    int spriteOffset = m_SpriteTableWidget->currentIndex().row();
    int spriteCnt = m_SpriteTableWidget->model()->rowCount();
    QGraphicsTextItem *isExistTextItem = NULL;

    for (int i = 0; i < listData.count(); ++i){
        isExistTextItem = listData[i].m_pIItem->m_TextItem;
        w.writeStartElement(QLatin1String(CellData.toLatin1()));
        // 레이어를 아이디로 사용하게됨
        // 레이어와 아이디를 분리
//        listData[i].m_pIItem->setZValue(m_iSavigAniIdnex + i * 0.0001f);
//        if(listData[i].m_iSpriteIndex > spriteOffset)
//        {
//            w.writeAttribute(QLatin1String(ImgIndex), QString::number(listData[i].m_iImgIndex));
//            w.writeAttribute(QLatin1String(SprIndex), QString::number(listData[i].m_iSpriteIndex + spriteCnt - spriteOffset - 1));
//        }
        if(isExistTextItem){
            listData[i].m_iImgIndex= -1;
            listData[i].m_iSpriteIndex = -1;
        }

        w.writeAttribute(QLatin1String(ImgIndex), QString::number(listData[i].m_iImgIndex));
        w.writeAttribute(QLatin1String(SprIndex), QString::number(listData[i].m_iSpriteIndex));

        //JistCommonData sData = m_SpriteData[listData[i].m_iImgIndex][listData[i].m_iSpriteIndex];
        //QRect sprRect = sData.m_Rect;
        // 중앙정렬
        w.writeAttribute(QLatin1String(pos_x), QString::number(listData[i].m_pIItem->pos().x()));
        w.writeAttribute(QLatin1String(pos_y), QString::number(listData[i].m_pIItem->pos().y()));
        // 좌상정렬
        //w.writeAttribute(QLatin1String(pos_x), QString::number(listData[i].m_pIItem->pos().x() - sprRect.width()/2));
        //w.writeAttribute(QLatin1String(pos_y), QString::number(640 - (listData[i].m_pIItem->pos().y() - sprRect.height()/2)));

        w.writeAttribute(QLatin1String(pos_z), QString::number(listData[i].m_pIItem->zValue()));
        w.writeAttribute(QLatin1String(alphaStr), QString::number(listData[i].m_pIItem->opacity()));
        w.writeAttribute(QLatin1String(scaleStr), QString::number(listData[i].m_pIItem->scale()));
        w.writeAttribute(QLatin1String(rotStr), QString::number(listData[i].m_pIItem->rotation()));
        w.writeAttribute(QLatin1String(flip_h), QString::number(listData[i].m_pIItem->m_FlipH));
        w.writeAttribute(QLatin1String(flip_v), QString::number(listData[i].m_pIItem->m_FlipV));
        w.writeAttribute(QLatin1String(effStr), QString::number(listData[i].m_pIItem->m_composition_mode));
        w.writeAttribute(QLatin1String(oX), QString::number(listData[i].m_pIItem->m_oIndex_X));
        w.writeAttribute(QLatin1String(oY), QString::number(listData[i].m_pIItem->m_oIndex_Y));
        int posX[3] = { X1, X2, X3};
        int posY[3] = { Y1, Y2, Y3};
        int dX = listData[i].m_pIItem->pos().x() - posX[listData[i].m_pIItem->m_oIndex_X];
        int dY = listData[i].m_pIItem->pos().y() - posY[listData[i].m_pIItem->m_oIndex_Y];
        const QPoint p(listData[i].m_pIItem->pos().x() - posX[listData[i].m_pIItem->m_oIndex_X]
                                                 ,listData[i].m_pIItem->pos().y() - posY[listData[i].m_pIItem->m_oIndex_Y] );

        listData[i].m_Pos = listData[i].m_pIItem->getRelativePos();

        w.writeAttribute(QLatin1String(dXStr), QString::number(dX));
        w.writeAttribute(QLatin1String(dYStr), QString::number(dY));
        QSizeF sizeXY(listData[i].m_pIItem->scaleXY());
        if(isExistTextItem){
            qreal size = listData[i].m_pIItem->m_TextItem->font().pointSizeF();
//            QFontInfo info(listData[i].m_pIItem->m_TextItem->font());
//            int ps = info.pixelSize();
//            int pos = info.pointSize();
            w.writeAttribute(QLatin1String(scaleXStr), QString::number((size/g_FontSize)));
            w.writeAttribute(QLatin1String(scaleYStr), QString::number((size/g_FontSize)));
        }
        else{
            w.writeAttribute(QLatin1String(scaleXStr), QString::number(sizeXY.width()));
            w.writeAttribute(QLatin1String(scaleYStr), QString::number(sizeXY.height()));
        }
        w.writeAttribute(QLatin1String("name"), listData[i].m_Name);
        if(isExistTextItem)
            w.writeAttribute(QLatin1String("anc"), QString::number(listData[i].m_pIItem->m_iAnchor));
        w.writeEndElement();
    }
}


void JistDocument::saveCellDataToBinary(QXmlStreamWriter &w, QList< JistCommonData > &listData, int index)
{

    // 정보 저장
    int imgOffset = this->m_iCurrentSpriteDataIndex;
    int spriteOffset = m_SpriteTableWidget->currentIndex().row();
    int spriteCnt = m_SpriteTableWidget->model()->rowCount();
    QGraphicsTextItem *isExistTextItem = NULL;

    JistCellData cellData;
    for (int i = 0; i < listData.count(); ++i){
        isExistTextItem = listData[i].m_pIItem->m_TextItem;
	//w.writeStartElement(QLatin1String("xxxx"));
        // 레이어를 아이디로 사용하게됨
        // 레이어와 아이디를 분리
//        listData[i].m_pIItem->setZValue(m_iSavigAniIdnex + i * 0.0001f);
//        if(listData[i].m_iSpriteIndex > spriteOffset)
//        {
//            w.writeAttribute(QLatin1String(ImgIndex), QString::number(listData[i].m_iImgIndex));
//            w.writeAttribute(QLatin1String(SprIndex), QString::number(listData[i].m_iSpriteIndex + spriteCnt - spriteOffset - 1));
//        }
        if(isExistTextItem){
            listData[i].m_iImgIndex= -1;
            listData[i].m_iSpriteIndex = -1;
        }

	//w.writeAttribute(QLatin1String(ImgIndex), QString::number(listData[i].m_iImgIndex));
	//w.writeAttribute(QLatin1String(SprIndex), QString::number(listData[i].m_iSpriteIndex));

        cellData.m_iImgIndex = listData[i].m_iImgIndex;
        cellData.m_iSpriteIndex = listData[i].m_iSpriteIndex;

        // 중앙정렬
	//w.writeAttribute(QLatin1String(pos_x), QString::number(listData[i].m_pIItem->pos().x()));
	//w.writeAttribute(QLatin1String(pos_y), QString::number(listData[i].m_pIItem->pos().y()));
        cellData.m_Px = listData[i].m_pIItem->pos().x();
        cellData.m_Py = 640 -  listData[i].m_pIItem->pos().y();
        // 좌상정렬
	////w.writeAttribute(QLatin1String(pos_x), QString::number(listData[i].m_pIItem->pos().x() - sprRect.width()/2));
	////w.writeAttribute(QLatin1String(pos_y), QString::number(640 - (listData[i].m_pIItem->pos().y() - sprRect.height()/2)));

	//w.writeAttribute(QLatin1String(pos_z), QString::number(listData[i].m_pIItem->zValue()));
	//w.writeAttribute(QLatin1String(alphaStr), QString::number(listData[i].m_pIItem->opacity()));
	//w.writeAttribute(QLatin1String(scaleStr), QString::number(listData[i].m_pIItem->scale()));
	//w.writeAttribute(QLatin1String(rotStr), QString::number(listData[i].m_pIItem->rotation()));
	//w.writeAttribute(QLatin1String(flip_h), QString::number(listData[i].m_pIItem->m_FlipH));
	//w.writeAttribute(QLatin1String(flip_v), QString::number(listData[i].m_pIItem->m_FlipV));
	//w.writeAttribute(QLatin1String(effStr), QString::number(listData[i].m_pIItem->m_composition_mode));
	//w.writeAttribute(QLatin1String(oX), QString::number(listData[i].m_pIItem->m_oIndex_X));
	//w.writeAttribute(QLatin1String(oY), QString::number(listData[i].m_pIItem->m_oIndex_Y));
        cellData.m_Zlayer = listData[i].m_pIItem->zValue();
        cellData.m_fAlpha = listData[i].m_pIItem->opacity();
        cellData.m_fScale = listData[i].m_pIItem->scale();
        cellData.m_iRot = listData[i].m_pIItem->rotation();
        cellData.m_bFlip_H = listData[i].m_pIItem->m_FlipH;
        cellData.m_bFlip_V = listData[i].m_pIItem->m_FlipV;
        cellData.m_iEff = listData[i].m_pIItem->m_composition_mode;
        cellData.m_OrgX = listData[i].m_pIItem->m_oIndex_X;
        cellData.m_OrgY = listData[i].m_pIItem->m_oIndex_Y;
        int posX[3] = { X1, X2, X3};
        int posY[3] = { Y1, Y2, Y3};
        int dX = listData[i].m_pIItem->pos().x() - posX[listData[i].m_pIItem->m_oIndex_X];
        int dY = listData[i].m_pIItem->pos().y() - posY[listData[i].m_pIItem->m_oIndex_Y];
        const QPoint p(listData[i].m_pIItem->pos().x() - posX[listData[i].m_pIItem->m_oIndex_X]
                                                 ,listData[i].m_pIItem->pos().y() - posY[listData[i].m_pIItem->m_oIndex_Y] );

        listData[i].m_Pos = listData[i].m_pIItem->getRelativePos();

	//w.writeAttribute(QLatin1String(dXStr), QString::number(dX));
	//w.writeAttribute(QLatin1String(dYStr), QString::number(dY));
        cellData.m_iDX = dX;
        cellData.m_iDY = dY;
        QSizeF sizeXY(listData[i].m_pIItem->scaleXY());
        if(isExistTextItem){
            qreal size = listData[i].m_pIItem->m_TextItem->font().pointSizeF();
//            QFontInfo info(listData[i].m_pIItem->m_TextItem->font());
//            int ps = info.pixelSize();
//            int pos = info.pointSize();
            w.writeAttribute(QLatin1String(scaleXStr), QString::number((size/g_FontSize)));
            w.writeAttribute(QLatin1String(scaleYStr), QString::number((size/g_FontSize)));
            cellData.m_fScaleX = (size/g_FontSize);
            cellData.m_fScaleY =(size/g_FontSize);
        }
        else{
	    //w.writeAttribute(QLatin1String(scaleXStr), QString::number(sizeXY.width()));
	    //w.writeAttribute(QLatin1String(scaleYStr), QString::number(sizeXY.height()));
            cellData.m_fScaleX = sizeXY.width();
            cellData.m_fScaleY = sizeXY.height();
        }
	//w.writeAttribute(QLatin1String("name"), listData[i].m_Name);
	//if(isExistTextItem)
	    //w.writeAttribute(QLatin1String("anc"), QString::number(listData[i].m_pIItem->m_iAnchor));


        w.writeStartElement(QLatin1String("lbl"));
        w.writeAttribute(QLatin1String("name"), listData[i].m_Name);
        if(isExistTextItem)
            w.writeAttribute(QLatin1String("anc"), QString::number(listData[i].m_pIItem->m_iAnchor));
        w.writeEndElement();
	//w.writeEndElement();
	if(m_isAddingBinData)
	    m_Binary.append(cellData);
    }
}


bool JistDocument::loadFile(QString path)
{
    m_isLoading = true;
    QString fileName = path;
    if(path.isEmpty())
        fileName = QFileDialog::getOpenFileName(m_ImageTableWidget, tr(" Load File"), tr(""), tr("save files (*.ans *.ansbak)"));

    if (!fileName.isEmpty()) {
        newDocument();
        QFile file(fileName);
        setDocName(fileName);
		if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::information(m_ImageTableWidget, tr("Unable to open file"), file.errorString());
            m_isLoading = false;
            return false;
        }
        loadImage(&file);
        m_undoStack->clear();
        m_isLoading = false;
        m_isAddedResource = false;
        return true;
    }

}

void JistDocument::loadImage(QIODevice *device)
{
    // 이미지 리스트 정리
    m_ImageListModel.reset();
    m_ImageData.clear();
    m_ImageListModel.setDataList(&m_ImageData);

    // 스프라이트 리스트 정리
	for(int k = 0; k < m_SpriteData.count(); k++){
        m_SpriteData[k].clear();
    }
    // 애니메이션 리스트 정리
    m_AniListModel.reset();
    m_AnimationData.clear();
    m_AniListModel.setDataList(&m_AnimationData);

    for(int h = 0; h < (m_CellData).count(); h++)
    {
        for(int i = 0; i < (m_CellData[h]).count(); i++)
        {
            for(int k = 0; k < m_CellData[h][i].count(); k++)
            {
                // 현재 셀 비표시하기
                //(m_CellData[h][i][k]).m_pIItem->setVisible(false);
                m_pSceneFrameFigure->m_canvas.removeItem(m_CellData[h][i][k].m_pIItem);
            }
        }
    }
    // 신 리스트 정리
    m_SceneListModel.reset();

    // 하위 깊이부터 차례로 지운다
    for(int k = 0; k < m_SceneData.count(); k++){

        // 셀 리스트 정리
        for(int j = 0; j < m_CellData[k].count(); j++)
            m_CellData[k][j].clear();
        m_SceneData[k].clear();
        m_CellData[k].clear();
    }
    m_CellData.clear();
    // 새로 만들기
    m_CellData.resize(1);
    m_CellData[0].resize(1);
    m_SceneData.resize(1);
    m_iPreSceneDataIndex = 0;
    //m_iCurrentSceneDataIndex = 0;
    m_iCurrentCellDataIndex = 0;
    m_SceneListModel.setDataList(&m_SceneData[0]);
    m_CellListModel.setDataList(&m_CellData[0][0]);

    xml.setDevice(device);
	xml.readNextStartElement() ;
	QString st = xml.name().toString();
	if(xml.name() == "Ani"){

        const QXmlStreamAttributes atts = xml.attributes();
        m_fLoadingVersion = atts.value(QLatin1String("version")).toString().toFloat();
		m_FinalWorkPath = atts.value(QLatin1String("AniPath")).toString();
        if(m_fLoadingVersion < 0.97)
        {
            ImageData = tr("ImageData");
            SpriteData = tr("objCell");
            rect_width = "rw";
            rect_height = "rh";
            rect_x = "rx";
            rect_y = "ry";
            AnimationData = tr("AnimationData");
            SceneData = tr("SceneData");
            CellData = tr("CellData");

            ImgIndex = "ImgIndex";
            SprIndex = "SprIndex";
            pos_x = "pos_x";
            pos_y = "pos_y";
            pos_z = "pos_z";
            alphaStr = "alpha";
            scaleStr = "scale";
            rotStr = "rot";
            flip_h = "flip_h";
            flip_v = "flip_v";
            effStr = "eff";
            oX = "oX";
            oY = "oY";
            dXStr = "dX";
            dYStr = "dY";
            scaleXStr = "sX";
            scaleYStr = "sY";
        }
        else
        {
            ImageData = tr("IDt");
            SpriteData = tr("objCell");
            rect_width = "rw";
            rect_height = "rh";
            rect_x = "rx";
            rect_y = "ry";
            AnimationData = tr("ADt");
            SceneData = tr("SDt");
            CellData = tr("CDt");

            ImgIndex = "Ix";
            SprIndex = "Sx";
            pos_x = "px";
            pos_y = "py";
            pos_z = "pz";
            alphaStr = "al";
            scaleStr = "sc";
            rotStr = "ro";
            flip_h = "fh";
            flip_v = "fv";
            effStr = "ef";
            oX = "oX";
            oY = "oY";
            dXStr = "dX";
            dYStr = "dY";
            scaleXStr = "sX";
            scaleYStr = "sY";
        }

        while(xml.readNextStartElement())
        {
            if(xml.name() == ImageData)
                loadImage();
            else if(xml.name() == AnimationData)
                loadAnimation();
        }
    }
    else {
        xml.raiseError(tr("Not a Ani file."));
    }
}


void JistDocument::loadImageSet(QIODevice *device, QString imgSetPath)
{
    xml.setDevice(device);
    if(xml.readNextStartElement() && xml.name() == "Ani"){

        const QXmlStreamAttributes atts = xml.attributes();
        //m_fLoadingVersion = atts.value(QLatin1String("version")).toString().toFloat();
        while(xml.readNextStartElement())
        {
            if(xml.name() == ImageData)
                loadImage(imgSetPath);
        }
    }
    else {
        xml.raiseError(tr("Not a Ani file."));
    }
}


void JistDocument::loadImage(QString imgSetPath)
{
    //Q_ASSERT(xml.isStartElement() && xml.name() == ImageData);

    const QXmlStreamAttributes atts = xml.attributes();
    const QString path = atts.value(QLatin1String("path")).toString();
    QDir dirC(m_strDocName);
    QString curFilneName = dirC.dirName();
    QString curPath = m_strDocName;
    curPath.remove(curFilneName);
    //bool r = QDir::setCurrent(curPath);
    QString relativePath;
    QDir dir = QDir::current();
    QString currendDirectory = dir.absolutePath();
    if(imgSetPath.isEmpty())
        relativePath = dir.relativeFilePath(path);
    else{
        QDir dirC(imgSetPath);
        QString curFilneName = dirC.dirName();
        QString imgAbsolPath = curPath;
        //imgAbsolPath.remove(curFilneName);
        imgAbsolPath.append(path);
        relativePath = dir.relativeFilePath(imgAbsolPath);
    }
    if(relativePath.contains(tr(".pvr.gz"))){
        relativePath.replace(tr(".pvr.gz"), tr(".png"));
    }
    if(!addSpriteList(relativePath)){

        return;
    }


    while(xml.readNextStartElement()){
        // seok 프로퍼티
        if (xml.name() == QLatin1String("properties")){
            JistCommonData &data = m_ImageData.last();
            data.m_Object.mergeProperties(readProperties());
        }else if (xml.name() == "objCell"){
            QImage img = ((m_ImageData.value(m_iCurrentSpriteDataIndex)).m_img);
            loadSprite(&img);
        }else{
            xml.skipCurrentElement();
        }
    }
    changeSpriteList(m_iCurrentSpriteDataIndex);
}

JistCommonData* JistDocument::loadSprite(QImage *img)
{
    Q_ASSERT(xml.isStartElement() && xml.name() == SpriteData);

    const QXmlStreamAttributes atts = xml.attributes();

    {
        QString rw = QLatin1String(rect_width);
        const int width = atts.value(QLatin1String(rect_width)).toString().toInt();
        const int height = atts.value(QLatin1String(rect_height)).toString().toInt();
        const int x = atts.value(QLatin1String(rect_x)).toString().toInt();
        const int y = atts.value(QLatin1String(rect_y)).toString().toInt();
        // 충돌영역
        const int cWidth = atts.value(QLatin1String("cw")).toString().toInt();
        const int cHeight = atts.value(QLatin1String("ch")).toString().toInt();
        const int cx = atts.value(QLatin1String("cx")).toString().toInt();
        const int cy = atts.value(QLatin1String("cy")).toString().toInt();

        const int uiOpt = atts.value(QLatin1String("UIOpt")).toString().toInt();
        QRect rect(x, y, width, height);
        QRect colisionRect(cx, cy, cWidth, cHeight);
        QImage  cutImage = img->copy(rect);
        if(rect.width() == 0)
            cutImage = g_EmptyImage;
        JistCommonData data;
        data.m_bVisible = false;
        data.m_Name = tr("");
        data.m_Rect = rect;
        data.m_CollisionRect = colisionRect;
        data.m_img = cutImage;
        data.m_UIOpt = uiOpt;
        data.m_iSpriteIndex = m_SpriteData[m_iCurrentSpriteDataIndex].count();
        m_SpriteData[m_iCurrentSpriteDataIndex].append(data);
        m_SpriteData[m_iCurrentSpriteDataIndex].last().m_iImgIndex  = m_iCurrentSpriteDataIndex;
        m_SpriteData[m_iCurrentSpriteDataIndex].last().m_iSpriteIndex = data.m_iSpriteIndex;
        // seok 프로퍼티
        while(xml.readNextStartElement()){
            if (xml.name() == QLatin1String("properties")){
                JistCommonData &data = m_SpriteData[m_iCurrentSpriteDataIndex].last();
                data.m_Object.mergeProperties(readProperties());
                if(!data.m_Object.properties().value(tr("ancX")).isEmpty()){
                    int x = data.m_Object.properties().value(QString(tr("ancX"))).toInt();
                    data.m_AnchorPoint.setX(x);
                }else{
                    data.m_Object.setProperty(tr("ancX"), QString::number(data.width()/2));
                    data.m_AnchorPoint.setX(data.width()/2);
                }
                if(!data.m_Object.properties().value(tr("ancY")).isEmpty()){
                    int y = data.m_Object.properties().value(QString(tr("ancY"))).toInt();
                    data.m_AnchorPoint.setY(y);
                }else{
                    data.m_Object.setProperty(tr("ancY"), QString::number(data.height()/2));
                    data.m_AnchorPoint.setY(data.height()/2);
                }
                QString name = data.m_Object.properties().value(QString(tr("name")));
                data.SetName(name);
            }else{
                xml.skipCurrentElement();
            }
        }
        // 강제 anchorPoint 넣어주기
        for(int k = 0; k < m_SpriteData[m_iCurrentSpriteDataIndex].count(); k++){
            JistCommonData *tempData = &m_SpriteData[m_iCurrentSpriteDataIndex][k];
            if(tempData->m_Object.properties().value(tr("ancX")).isEmpty()){
                int x = tempData->width()/2;
                tempData->m_AnchorPoint.setX(x);
                tempData->m_Object.setProperty(tr("ancX"), QString::number(x));
            }
            if(tempData->m_Object.properties().value(tr("ancY")).isEmpty()){
                int y = tempData->height()/2;
                tempData->m_AnchorPoint.setY(y);
                tempData->m_Object.setProperty(tr("ancY"), QString::number(y));
            }
        }
        return &data;
    }
}

void JistDocument::loadAnimation()
{
    Q_ASSERT(xml.isStartElement() && xml.name() == AnimationData);

    const QXmlStreamAttributes atts = xml.attributes();
    QString name = atts.value(QLatin1String("name")).toString();
    if(name.isEmpty())
        name = tr("Animation");
    //QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    //char *fixCandiName[7] = {"대기","맞기","효과","일반공격","스킬공격","주문공격", ""};
    //QString fixName = codec->toUnicode(fixCandiName[m_iPreSceneDataIndex]);

    addAnimation(name, true);
    //changeSceneList(m_iCurrentSceneDataIndex);
    while(xml.readNextStartElement()){
        if (xml.name() == SceneData){
            loadScene();
        }
    }
}

void JistDocument::loadScene()
{
    Q_ASSERT(xml.isStartElement() && xml.name() == SceneData);

    const QXmlStreamAttributes atts = xml.attributes();
    addScene();
    int layNo = 0;
    while(xml.readNextStartElement()){
		QString st = xml.name().toString();
        if (xml.name() == CellData || xml.name() == CellData2){
            loadCell(layNo++);
        }
		else{
			xml.skipCurrentElement();
		}
    }

    // 선택하지 않음 0.9961 버전
    m_CellTableWidget->clearSelection();
    //changeCellList(m_iCurrentCellDataIndex);
}

void JistDocument::loadCell(int layNo)
{
    //Q_ASSERT(xml.isStartElement() && xml.name() == CellData);

    const QXmlStreamAttributes atts = xml.attributes();

    {
        int imgIndex = atts.value(QLatin1String(ImgIndex)).toString().toInt();
        int sprIndex = atts.value(QLatin1String(SprIndex)).toString().toInt();
        const int x = atts.value(QLatin1String(pos_x)).toString().toFloat();
        const int y = atts.value(QLatin1String(pos_y)).toString().toFloat();
        const qreal z = atts.value(QLatin1String(pos_z)).toString().toFloat();
        const qreal alpha = atts.value(QLatin1String(alphaStr)).toString().toFloat();
        const qreal scale = atts.value(QLatin1String(scaleStr)).toString().toFloat();
        const qreal rot = atts.value(QLatin1String(rotStr)).toString().toFloat();
        const bool flipH = atts.value(QLatin1String(flip_h)).toString().toInt();
        const bool flipV = atts.value(QLatin1String(flip_v)).toString().toInt();
        int eff = atts.value(QLatin1String(effStr)).toString().toInt();
        const int orgX = atts.value(QLatin1String(oX)).toString().toInt();
        const int orgY = atts.value(QLatin1String(oY)).toString().toInt();
        const int dX = atts.value(QLatin1String(dXStr)).toString().toInt();
        const int dY = atts.value(QLatin1String(dYStr)).toString().toInt();
        const qreal scaleX = atts.value(QLatin1String(scaleXStr)).toString().toFloat();
        const qreal scaleY = atts.value(QLatin1String(scaleYStr)).toString().toFloat();
        const QString  name = atts.value(QLatin1String("name")).toString();
        const int  anchor = atts.value(QLatin1String("anc")).toString().toInt();


        JistCommonData srcData;
        QImage img = QImage();
        srcData.m_img = img;
        // 지워진 이미지에 대해 남은 셀에 대한 처리
        if((0 <= sprIndex && 0 <= imgIndex) && imgIndex < m_SpriteData.count() && sprIndex < m_SpriteData[imgIndex].count())
            srcData = m_SpriteData[imgIndex][sprIndex];
        else{
            // 빈 셀
            srcData.m_img  = g_EmptyImage;
            imgIndex = -1;
            sprIndex = -1;
        }
        JistCommonData data;
        data.m_Name = name;
       // data.m_pIItem->m_Text = data.m_Name;
        data.m_bVisible = true;
        //data.m_Name = "T";
        //data.m_Rect = srcData.m_Rect;
        data.m_img = srcData.m_img;

        data.m_Pos = QPoint(dX, dY);
        //data.m_Zlayer = z;
        data.m_iImgIndex = imgIndex;
        data.m_iSpriteIndex = sprIndex;

        //ImageItem* i = new ImageItem(&data.m_img);
        //data.m_pIItem = new ImageItem(&data.m_img);
        data.m_pIItem = new ImageItem(data.m_iImgIndex, data.m_iSpriteIndex, &m_SpriteData);
        //로딩속도 개선을 위한 작업
        data.m_pIItem->m_bEffDraw = false;
        data.m_pIItem ->setZValue(z);
        data.m_pIItem ->setId(layNo);
        m_pSceneFrameFigure->addItem(data.m_pIItem);
        data.m_pIItem->setPos(QPointF(x, y));
        data.m_pIItem->setOpacity(alpha);
        data.m_pIItem->setScale(scale);
        data.m_pIItem->m_iAnchor = anchor;
        if(!data.m_Name.isEmpty()){
            //QGraphicsTextItem *textSprite;
            //m_pSceneFrameFigure->m_canvas.setBackgroundBrush( pm );
            //data.m_pIItem->m_TextItem = new QGraphicsTextItem( name, data.m_pIItem, &m_pSceneFrameFigure->m_canvas );
            data.m_pIItem->m_TextItem = new QGraphicsTextItem( name, data.m_pIItem);
            QGraphicsTextItem *textItem = data.m_pIItem->m_TextItem;
            //QFont font( QString("나눔고딕 ExtraBold"), 10 * scaleX + 0.5);
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
            QFont font( localeStr, g_FontSize * scaleX + 0.5 );
            data.m_pIItem->m_TextItem->setFont( font );
            QRectF r = data.m_pIItem->m_TextItem->boundingRect();
            data.m_pIItem->setRect(r);
            data.m_pIItem->m_TextItem->setCacheMode(QGraphicsItem::NoCache);
            data.m_pIItem->m_TextItem->setPos(-r.width()/2, -r.height()/2);
            data.m_pIItem->m_TextItem->setDefaultTextColor(QColor(255,255,255));
    // data.m_img.fill(0);

     //data.m_pIItem->m_Image.fill(0);

            switch(data.m_pIItem->m_iAnchor)
            {
                case 0:
                {
                    textItem->setPos(-r.width()/2, -r.height()/2);
                }
                break;
                case 1:
                {
                    textItem->setPos(0, -r.height()/2);
                }
                break;
                case 2:
                {
                    textItem->setPos(-r.width(), -r.height()/2);
                }
                break;
                case 3:
                {
                    textItem->setPos(-r.width()/2, -r.height());
                }
                break;
                case 4:
                {
                    textItem->setPos(0, -r.height());
                }
                break;
                case 5:
                {
                    textItem->setPos(-r.width(), -r.height());
                }
                break;
                case 6:
                {
                    textItem->setPos(-r.width()/2, 0);
                }
                break;
                case 7:
                {
                    textItem->setPos(-r.width(), 0);
                }
                break;
                case 8:
                {
                    textItem->setPos(0, 0);
                }
                break;
            }
            // 텍스트 색상
            switch(eff)
            {
                case 100:
                case 12:
                {
                    textItem->setDefaultTextColor(QColor(225, 182, 52));
                    eff = 100;
                }
                break;
                case 101:
                case 13:
                {
                   textItem->setDefaultTextColor(QColor(145, 185, 3));
                   eff = 101;
                }
                break;
                case 102:
                case 14:
                {
                    textItem->setDefaultTextColor(QColor(163, 95, 198));
                    eff = 102;
                }
                break;
                case 103:
                case 16:
                {
                    textItem->setDefaultTextColor(QColor(2, 15, 41));
                    eff = 103;
                }
                break;
            }
        }
        else{
            if(scaleX != 0)
                data.m_pIItem->setScaleX(scaleX);
            if(scaleY != 0)
                data.m_pIItem->setScaleY(scaleY);
        }
        data.m_pIItem->setRotation(rot);
        data.m_pIItem->m_FlipH = flipH;
        data.m_pIItem->m_FlipV = flipV;
        data.m_pIItem->m_Image = data.m_img.mirrored(flipH, flipV);
        data.m_pIItem->m_composition_mode = eff;
        // 중앙정렬이전버전
        if(m_fLoadingVersion < 0.959)
        {
            int ch_X = dX + data.m_pIItem->m_Image.size().width()/2;
            int ch_Y = dY + data.m_pIItem->m_Image.size().height()/2;
            data.m_pIItem->m_RelativePos = QPoint(ch_X, ch_Y);
        }
        else{
            data.m_pIItem->m_RelativePos = QPoint(dX, dY);
        }

        data.m_pIItem->m_oIndex_X = orgX;
        data.m_pIItem->m_oIndex_Y = orgY;
        if(m_fLoadingVersion == 1.0)
        {
            data.m_pIItem->setPosInit();
            data.m_pIItem->setOriginPos(orgX, orgY);
        }
        else//(m_fLoadingVersion != 1.0)
        {
            //data.m_pIItem->setRelativePos();
            data.m_pIItem->setOriginPosInit(orgX, orgY);
        }

        // 로딩속도 현저한 감소
        data.m_pIItem->m_bEffDraw = true;
        data.m_pIItem->recalculateResult();

        //m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][m_CellListModel.rowCount() - 1] = data;
        m_CellListModel.insertData(m_CellListModel.rowCount(), &data);
        m_CellTableWidget->refineViewNoUndo(m_CellListModel.rowCount()-1);
        m_SceneListModel.setData(m_SceneTableWidget->currentIndex(), m_CellListModel.rowCount(), Qt::UserRole+4);
        xml.skipCurrentElement();
    }
}

void JistDocument::newDocument()
{
    m_pSrcFigure->clear();
    m_SpriteUnitFigure->clear();
    m_pAnimationFigure->resetAni();
    // 이미지 리스트 정리
    m_ImageListModel.reset();
    m_ImageData.clear();
    m_ImageListModel.setDataList(&m_ImageData);

    // 스프라이트 리스트 정리
    m_SpriteListModel.reset();
    for(int k = 0; k < m_SpriteData.count(); k++){
        m_SpriteData[k].clear();
    }
    // 애니메이션 리스트 정리
    m_AniListModel.reset();
    m_AnimationData.clear();
    m_AniListModel.setDataList(&m_AnimationData);

    // 신 리스트 정리
    m_SceneListModel.reset();
    // 셀 리스트 정리
    m_CellListModel.reset();

//    for(int h = 0; h < (m_CellData).count(); h++)
//    {
//        for(int i = 0; i < (m_CellData[h]).count(); i++)
//        {
//            for(int k = 0; k < m_CellData[h][i].count(); k++)
//            {
//                // 현재 셀 비표시하기
//                (m_CellData[h][i][k]).m_pIItem->setVisible(false);
//            }
//        }
//    }
    // 신 리스트 정리
    m_SceneListModel.reset();

    // 하위 깊이부터 차례로 지운다
    for(int k = 0; k < m_SceneData.count(); k++){

        // 셀 리스트 정리
        for(int j = 0; j < m_CellData[k].count(); j++)
            m_CellData[k][j].clear();
        m_SceneData[k].clear();
        m_CellData[k].clear();
    }
    m_CellData.clear();
    // 새로 만들기
    m_CellData.resize(1);
    m_CellData[0].resize(1);
    m_SceneData.resize(1);
    m_iPreSceneDataIndex = 0;
    //m_iCurrentSceneDataIndex = 0;
    m_iCurrentCellDataIndex = 0;
    m_SceneListModel.setDataList(&m_SceneData[0]);
    m_CellListModel.setDataList(&m_CellData[0][0]);

    m_pSceneFrameFigure->clear();
    m_undoStack->clear();
    m_isAddedResource = false;
    //m_pAnimationFigure->m_CellData.clear();
}

// 애니메이션 리스트뷰에서 제거
void JistDocument::clearAniList()
{
    // 애니메이션 리스트 정리
    m_AniListModel.reset();
    m_AnimationData.clear();
    m_AniListModel.setDataList(&m_AnimationData);

    // 신 리스트 정리
    m_SceneListModel.reset();
    // 셀 리스트 정리
    //m_CellListModel.reset();

    // 신 리스트 정리
    //m_SceneListModel.reset();

    // 하위 깊이부터 차례로 지운다
    for(int k = 0; k < m_SceneData.count(); k++){
        m_SceneData[k].clear();
        //m_CellData[k].clear();
    }
    m_CellData.clear();
    // 새로 만들기
    m_CellData.resize(1);
    m_CellData[0].resize(1);
    m_SceneData.resize(1);
    m_iPreSceneDataIndex = 0;
    //m_iCurrentSceneDataIndex = 0;
    m_iCurrentCellDataIndex = 0;
    m_SceneListModel.setDataList(&m_SceneData[0]);
    m_CellListModel.setDataList(&m_CellData[0][0]);
    // 재생 애니메이션 번호 초기화
    m_pAnimationFigure->m_iAnimationIndex = 0;
}

void JistDocument::setOriginPosX1()
{
    for(int i = 0; i < m_CellData[m_iCurrentSceneDataIndex].count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iCurrentSceneDataIndex][i].count(); k++)
        {
            ImageItem *item = m_CellData[m_iCurrentSceneDataIndex][i][k].m_pIItem;
            if(item)
                item->setOriginPosInit(0, item->m_oIndex_Y);
        }
    }
}

void JistDocument::setOriginPosX2()
{
    for(int i = 0; i < m_CellData[m_iCurrentSceneDataIndex].count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iCurrentSceneDataIndex][i].count(); k++)
        {
            ImageItem *item = m_CellData[m_iCurrentSceneDataIndex][i][k].m_pIItem;
            if(item)
                item->setOriginPosInit(1, item->m_oIndex_Y);
        }
    }
}
void JistDocument::setOriginPosX3(){
    for(int i = 0; i < m_CellData[m_iCurrentSceneDataIndex].count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iCurrentSceneDataIndex][i].count(); k++)
        {
            ImageItem *item = m_CellData[m_iCurrentSceneDataIndex][i][k].m_pIItem;
            if(item)
                item->setOriginPosInit(2, item->m_oIndex_Y);
        }
    }
}
void JistDocument::setOriginPosY1()
{
    for(int i = 0; i < m_CellData[m_iCurrentSceneDataIndex].count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iCurrentSceneDataIndex][i].count(); k++)
        {
            ImageItem *item = m_CellData[m_iCurrentSceneDataIndex][i][k].m_pIItem;
            if(item)
                item->setOriginPosInit(item->m_oIndex_X, 0);
        }
    }
}
void JistDocument::setOriginPosY2()
{
    for(int i = 0; i < m_CellData[m_iCurrentSceneDataIndex].count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iCurrentSceneDataIndex][i].count(); k++)
        {
            ImageItem *item = m_CellData[m_iCurrentSceneDataIndex][i][k].m_pIItem;
            if(item)
                item->setOriginPosInit(item->m_oIndex_X, 1);
        }
    }
}
void JistDocument::setOriginPosY3()
{
    for(int i = 0; i < m_CellData[m_iCurrentSceneDataIndex].count(); i++)
    {
        for(int k = 0; k < m_CellData[m_iCurrentSceneDataIndex][i].count(); k++)
        {
            ImageItem *item = m_CellData[m_iCurrentSceneDataIndex][i][k].m_pIItem;
            if(item)
                item->setOriginPosInit(item->m_oIndex_X, 2);
        }
    }
}

void JistDocument::setAnchorTextItem(int index)
{
    if(!m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex].count())
        return;
    QModelIndexList selectedList = getSelectCellList();
    for(int k = 0; k < selectedList.count(); k++){
    //if(!selectedList.isEmpty()){
        int id = selectedList.at(k).row();
        QGraphicsTextItem *textItem =  m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_TextItem;
        if(textItem){
            QRectF r = textItem->boundingRect();
            //data.m_pIItem->setRect(r);
            textItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
            m_CellData[m_iCurrentSceneDataIndex][m_iCurrentCellDataIndex][id].m_pIItem->m_iAnchor = index;
            switch(index)
            {
                case 0:
                {
                    textItem->setPos(-r.width()/2, -r.height()/2);
                }
                break;
                case 1:
                {
                    textItem->setPos(0, -r.height()/2);
                }
                break;
                case 2:
                {
                    textItem->setPos(-r.width(), -r.height()/2);
                }
                break;
                case 3:
                {
                    textItem->setPos(-r.width()/2, -r.height());
                }
                break;
                case 4:
                {
                    textItem->setPos(0, -r.height());
                }
                break;
                case 5:
                {
                    textItem->setPos(-r.width(), -r.height());
                }
                break;
                case 6:
                {
                    textItem->setPos(-r.width()/2, 0);
                }
                break;
                case 7:
                {
                    textItem->setPos(-r.width(), 0);
                }
                break;
                case 8:
                {
                    textItem->setPos(0, 0);
                }
                break;
            }
        }
    }
}

void JistDocument::setScaleControl(QSpinBox * spX, QSpinBox * spY, QSlider *slX, QSlider *slY)
{
    m_ScaleXSpinBox = spX;
    m_ScaleYSpinBox = spY;
    m_ScaleXHorizontalSlider = slX;
    m_ScaleYHorizontalSlider = slY;
}

void JistDocument::loadImageOnTiled(QIODevice *device, Tiled::Map  *map)
{
    //int cnt = 0;
    xml.setDevice(device);
    xml.readNextStartElement();

    map->setJistObjectSet(&m_ImageData, &m_SpriteData);
    int groupCnt = 0;
    QList<Tiled::ObjectGroup*> groups = map->objectGroups();

    //if(!m_ImageListModel.m_pList)
    {
        // 이미지 리스트 정리
        m_ImageListModel.reset();
        m_ImageData.clear();
        if(!m_ImageListModel.m_pList)
            m_ImageListModel.setDataList(&m_ImageData);

        // 스프라이트 리스트 정리
        m_SpriteListModel.reset();
        for(int k = 0; k < m_SpriteData.count(); k++){
            m_SpriteData[k].clear();
        }
        if(!m_SpriteListModel.m_pList)
            m_SpriteListModel.setDataList(&m_SpriteData[0]);
    }
    while (xml.readNextStartElement()) {
        if (xml.name() == QLatin1String("objSet")){
            //cnt++;
            const QXmlStreamAttributes atts = xml.attributes();
            m_fLoadingVersion = atts.value(QLatin1String("version")).toString().toFloat();
            //QString st = atts.value(QLatin1String("path")).toString();
            m_FinalWorkPath = atts.value(QLatin1String("AniPath")).toString();
            if(m_fLoadingVersion < 0.97)
            {
                ImageData = tr("ImageData");
                SpriteData = tr("objCell");
                rect_width = "rw";
                rect_height = "rh";
                rect_x = "rx";
                rect_y = "ry";
                AnimationData = tr("AnimationData");
                SceneData = tr("SceneData");
                CellData = tr("CellData");

                ImgIndex = "ImgIndex";
                SprIndex = "SprIndex";
                pos_x = "pos_x";
                pos_y = "pos_y";
                pos_z = "pos_z";
                alphaStr = "alpha";
                scaleStr = "scale";
                rotStr = "rot";
                flip_h = "flip_h";
                flip_v = "flip_v";
                effStr = "eff";
                oX = "oX";
                oY = "oY";
                dXStr = "dX";
                dYStr = "dY";
                scaleXStr = "sX";
                scaleYStr = "sY";
            }
            else
            {
                ImageData = tr("IDt");
                SpriteData = tr("objCell");
                rect_width = "rw";
                rect_height = "rh";
                rect_x = "rx";
                rect_y = "ry";
                AnimationData = tr("ADt");
                SceneData = tr("SDt");
                CellData = tr("CDt");

                ImgIndex = "Ix";
                SprIndex = "Sx";
                pos_x = "px";
                pos_y = "py";
                pos_z = "pz";
                alphaStr = "al";
                scaleStr = "sc";
                rotStr = "ro";
                flip_h = "fh";
                flip_v = "fv";
                effStr = "ef";
                oX = "oX";
                oY = "oY";
                dXStr = "dX";
                dYStr = "dY";
                scaleXStr = "sX";
                scaleYStr = "sY";
            }
            const QString path = atts.value(QLatin1String("path")).toString();
            loadImage(path);
        }/*else if(xml.name() == QLatin1String("objectgroup")){
            Tiled::ObjectGroup* tempGroup = groups.at(groupCnt++);
            int objCnt = 0;
            while (xml.readNextStartElement()) {
                // 오브젝트 로드
                if (xml.name() == QLatin1String("object")){

                    const QXmlStreamAttributes atts = xml.attributes();
                    const QString name = atts.value(QLatin1String("name")).toString();
                    const unsigned gid = atts.value(QLatin1String("gid")).toString().toUInt();
                    const unsigned iid = atts.value(QLatin1String("iid")).toString().toUInt();
                    const unsigned sid = atts.value(QLatin1String("sid")).toString().toUInt();
                    const int x = atts.value(QLatin1String("x")).toString().toInt();
                    const int y = atts.value(QLatin1String("y")).toString().toInt();
                    const int width = atts.value(QLatin1String("width")).toString().toInt();
                    const int height = atts.value(QLatin1String("height")).toString().toInt();
                    const QString type = atts.value(QLatin1String("type")).toString();
                    const QStringRef visibleRef = atts.value(QLatin1String("visible"));

                   // const QPointF pos = pixelToTileCoordinates(mMap, x, y);
                   // const QPointF size = pixelToTileCoordinates(mMap, width, height);

                    Tiled::MapObject *object = tempGroup->objects()[objCnt++];

                    if (iid) {
                        JistCommonData* srcData = NULL;
                        // 0이면 없는 것이 사양이므로 -1 씩 뺴줌
                        srcData = &m_SpriteData[iid-1][sid-1];
                        object->setCell(srcData);
                    }
                    xml.skipCurrentElement();
                }else
                    xml.skipCurrentElement();
            }
        }*/
        else
            xml.skipCurrentElement();
    }
    xml.clear();
}

// seok 프로퍼티 =====================================================
Tiled::Properties JistDocument::readProperties()
{
    Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("properties"));

    Tiled::Properties properties;

    while (xml.readNextStartElement()) {
        if (xml.name() == QLatin1String("property"))
            readProperty(&properties);
        else
            xml.skipCurrentElement();
    }

    return properties;
}

void JistDocument::readProperty(Tiled::Properties *properties)
{
    Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("property"));

    const QXmlStreamAttributes atts = xml.attributes();
    QString propertyName = atts.value(QLatin1String("name")).toString();
    QString propertyValue = atts.value(QLatin1String("value")).toString();

    while (xml.readNext() != QXmlStreamReader::Invalid) {
        if (xml.isEndElement()) {
            break;
        } else if (xml.isCharacters() && !xml.isWhitespace()) {
            if (propertyValue.isEmpty())
                propertyValue = xml.text().toString();
        } else if (xml.isStartElement()) {
            xml.skipCurrentElement();
        }
    }

    properties->insert(propertyName, propertyValue);
}


void JistDocument::ClearList()
{
    //if(!m_ImageListModel.m_pList)
    {
        // 이미지 리스트 정리
        m_ImageListModel.reset();
        m_ImageData.clear();
        if(!m_ImageListModel.m_pList)
            m_ImageListModel.setDataList(&m_ImageData);

        // 스프라이트 리스트 정리
        m_SpriteListModel.reset();
        for(int k = 0; k < m_SpriteData.count(); k++){
            m_SpriteData[k].clear();
        }
        if(!m_SpriteListModel.m_pList)
            m_SpriteListModel.setDataList(&m_SpriteData[0]);
        m_pSrcFigure->clear();
        m_SpriteUnitFigure->clear();
    }
}
